library("ncdf4")
library("raster")
library("sf")
library("tidyverse")
library("plotly")

sst <- stack("input/cmems_mod_blk_phy-tem_my_2.5km_P1M-m_1715770301759.nc")
proj4string(sst)=CRS("+init=EPSG:4326")

# read grid 
grid <- read.csv("output/grid.csv")
spgrid <- SpatialPoints(cbind(grid$x, grid$y))

# get raster numbers
data <- grid
nrow <- dim(sst)[3]
for (i in 1:nrow) {
  print(paste0("Processing nrow: ", i))
  map <- sst[[i]]
  #df <- as.data.frame(map, xy=T) 
  vals <- raster::extract(map, spgrid, method="bilinear")
  
  colname <- names(map)
  data[,colname] <- vals
  
  #tsf <- st_as_sf(grid, coords = c("x", "y"))
  #plot(tsf)
}

# cleanup post-processing 
data <- na.omit(data)

# vizualize test
tsf <- st_as_sf(data, coords = c("x", "y"))
plot(tsf, max.plot=12)

# save output to csv 
write.csv(data, "output/sst-monthly.csv", row.names = F)



